package Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import Interface_Data.Course;
import Interface_Data.Stu;
import Vo.CourseChooseVo;


public class CourseAlgorithm {
	private List<CourseChooseVo> coursechooselist;
	
	private class Bag implements Comparable<Bag>{
		Stu stu;
		double rand;
		public Bag(Stu stu,double rand){
			this.stu=stu;
			this.rand=rand;
		}
		
		public Stu getStu(){
			return stu;
		}

		@Override
		public int compareTo(Bag arg0) {
			// TODO Auto-generated method stub
			if(rand<arg0.rand){
				return  1;
			}else if(rand==arg0.rand){
				return 0;
			}else{
				return -1;
			}
		}
		
		
	}
	
	
	public CourseAlgorithm(List<Stu> StuList,List<Course> CouList,int needScore){
		coursechooselist=new LinkedList<CourseChooseVo>();
		Map<Integer,Course> coursemap=new HashMap<Integer,Course>();
		Map<Integer,List<Stu>> stumap=new HashMap<Integer,List<Stu>>();
		Iterator<Stu> stuitr=StuList.iterator();
		while(stuitr.hasNext()){
			Stu stu=stuitr.next();
			List<Integer> list=stu.getChoose();
			for(int i=0;i<list.size();++i){
				if(stumap.containsKey(list.get(i))){
					stumap.get(list.get(i)).add(stu);
				}else{
					List<Stu> l=new ArrayList<Stu>();
					l.add(stu);
					stumap.put(list.get(i),l);
				}
			}
		}
		Iterator<Course> courseitr=CouList.iterator();
		while(courseitr.hasNext()){
			Course course=courseitr.next();
			coursemap.put(course.getId(), course);
		}
		
		Iterator<Integer> itr=coursemap.keySet().iterator();
		while(itr.hasNext()){
			Integer id=itr.next();
			List<Stu> list=stumap.get(id);
			if(list==null){
				continue;
			}
			Bag[] bags=new Bag[list.size()];
			for(int i=0;i<list.size();++i){
				bags[i]=new Bag(list.get(i),Math.random()*(needScore-list.get(i).getScore()+list.get(i).getGrade()));
			}
			Arrays.sort(bags);
			Course course=coursemap.get(id);
			int number=course.getNumber();
			if(bags.length<=course.getNumber())
			{
				number=bags.length;
			}
			for(int i=0;i<number;++i){
				Stu stu=bags[i].getStu();
				coursechooselist.add(new CourseChooseVo(id,stu.getId(),-1,stu.getGrade()));
				stu.setScore(stu.getScore()+course.getScore());
			}
		}
	}
	
	public List<CourseChooseVo> getCourseChooseList(){
		return coursechooselist;
	}
	
}
